<?php

namespace Biz\service\package;

use Biz\cache\course\OrderNoCache;
use Biz\model\package\PackageLogistics;
use Biz\module\Sys\ErrorConst;
use Doraemon\cache\Queue;
use Doraemon\pockets\action\ApiAction;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\IdParse;
use Doraemon\tools\Log;
use Biz\model\package\PackageOrder as mPackageOrder;
use hhz\constant\basic\UserExtendPhoneScene;
use Doraemon\model\Phone;

class PackageOrder
{
    const PACKAGE_ID_1 = 1; //基础包
    const PACKAGE_ID_2 = 2; //高级包
    const PACKAGE_ID_3 = 3; //分析助手

    const PACKAGE_GOOD_1 = 1; // 包裹商品1
    const PACKAGE_GOOD_2 = 2; // 包裹商品2
    const PACKAGE_GOOD_3 = 3; // 包裹商品3
    const PACKAGES = [
//        self::PACKAGE_ID_1 => ['title' => '好好住新人大礼包基础包', 'spec_img' => '', 'price' => '69', 'id' => self::PACKAGE_ID_1],
//        self::PACKAGE_ID_2 => ['title' => '好好住新人大礼包升级包', 'spec_img' => '', 'price' => '149', 'id' => self::PACKAGE_ID_2],
        self::PACKAGE_ID_1 => ['title' => '好好住新人大礼包基础包', 'spec_img' => '', 'teacher_img' =>'',  'price' => '0.01', 'id' => self::PACKAGE_ID_1],
        self::PACKAGE_ID_2 => ['title' => '好好住新人大礼包升级包', 'spec_img' => '', 'teacher_img' =>'', 'price' => '0.02', 'id' => self::PACKAGE_ID_2],
        self::PACKAGE_ID_3 => ['title' => '需求分析助手', 'spec_img' => 'https://img.haohaozhu.cn/Op-imageShow/0b2f7208c08c0gI00rx06sd?iv=1','teacher_img' => 'https://img.haohaozhu.cn/Op-imageShow/0b2f7208c08c0gI00rx06sd?iv=1', 'price' => '0', 'line_price' => '129','id' => self::PACKAGE_ID_3],
    ];

    // 权益解读
    const PACKAGE_RIGHT = '[{"id":1,"title":"需求分析助手","desc":"刚开始装修点什么？这本手册将为你各种装修疑惑修疑惑种装修疑惑修疑惑","cover_img":"https://img.haohaozhu.cn/Op-imageShow/40b1430v90h00k400ruqmmm?iv=1","price":23.9,"package_id":1,"introduce_img":"https://img.haohaozhu.cn/Op-imageShow/40b1430v90h00k400ruqmmm?iv=1"},{"id":2,"title":"新装100问","desc":"刚开始装修要做点什么？这本手册将为你全方位解答各种装修疑惑！好好住的编辑团队《新装指南》","cover_img":"https://img.haohaozhu.cn/Op-imageShow/40b1430v90h00k400ruqmmm?iv=1","price":23.9,"package_id":1,"introduce_img":"https://img.haohaozhu.cn/Op-imageShow/40b1430v90h00k400ruqmmm?iv=1"},{"id":3,"title":"装修告知书","desc":"你可以将该告知书贴在楼宇大堂、入户门外等位置，保障装修期间邻里和睦。同时为了保护隐私","cover_img":"https://img.haohaozhu.cn/Op-imageShow/40b1430v90h00k400ruqmmm?iv=1","price":69,"package_id":1,"introduce_img":"https://img.haohaozhu.cn/Op-imageShow/40b1430v90h00k400ruqmmm?iv=1"},{"id":4,"title":"开工御守","desc":"","cover_img":"https://img.haohaozhu.cn/Op-imageShow/40b1430v90h00k400ruqmmm?iv=1","price":69,"package_id":1,"introduce_img":"https://img.haohaozhu.cn/Op-imageShow/40b1430v90h00k400ruqmmm?iv=1"},{"id":5,"title":"定制资料夹","desc":"","cover_img":"https://img.haohaozhu.cn/Op-imageShow/40b1430v90h00k400ruqmmm?iv=1","price":69,"package_id":2,"introduce_img":"https://img.haohaozhu.cn/Op-imageShow/40b1430v90h00k400ruqmmm?iv=1"},{"id":6,"title":"好住冰箱贴","desc":"","cover_img":"https://img.haohaozhu.cn/Op-imageShow/40b1430v90h00k400ruqmmm?iv=1","price":69,"package_id":2,"introduce_img":"https://img.haohaozhu.cn/Op-imageShow/40b1430v90h00k400ruqmmm?iv=1"},{"id":7,"title":"入户门垫","desc":"","cover_img":"https://img.haohaozhu.cn/Op-imageShow/40b1430v90h00k400ruqmmm?iv=1","price":69,"package_id":2,"introduce_img":"https://img.haohaozhu.cn/Op-imageShow/40b1430v90h00k400ruqmmm?iv=1"}]';

    // 物流页和订单信息页用到
    const PACKAGES_GOODS = [
        self::PACKAGE_ID_1 => [
            self::PACKAGE_GOOD_1 => [
                ['title' => '新装指南', 'spec_img' => '', 'num' => '1', 'desc' => ''],
                ['title' => '装修告知书', 'spec_img' => '', 'num' => '1', 'desc' => ''],
                ['title' => '开工御守', 'spec_img' => '', 'num' => '1', 'desc' => ''],
                ['title' => '装修需求梳理工具', 'spec_img' => '', 'num' => '1', 'desc' => '线上工具购买后立即生效']
            ]
        ],
        self::PACKAGE_ID_2 => [
            self::PACKAGE_GOOD_1 => [
                ['title' => '新装指南', 'spec_img' => '', 'num' => '1', 'desc' => ''],
                ['title' => '装修告知书', 'spec_img' => '', 'num' => '1', 'desc' => ''],
                ['title' => '开工御守', 'spec_img' => '', 'num' => '1', 'desc' => ''],
                ['title' => '装修需求梳理工具', 'spec_img' => '', 'num' => '1', 'desc' => '线上工具购买后立即生效']
            ],
            self::PACKAGE_GOOD_2 => [
                ['title' => '配套冰箱贴', 'spec_img' => '', 'num' => '1', 'desc' => ''],
            ],
            self::PACKAGE_GOOD_3 => [
                ['title' => '入户门垫', 'spec_img' => '', 'num' => '1', 'desc' => ''],
            ]
        ],
    ];

    public static function getPackage($id)
    {
        return self::PACKAGES[$id];
    }

    public static function getOrderInfo($orderNo)
    {
        return mPackageOrder::getByWhere([
            'order_no' => $orderNo,
            'status' => mPackageOrder::STATUS_VALID
        ]);
    }

    /**
     * 获取已支付订单
     *
     * @param $uid
     * @param int $package 1、礼包1和2  3、需求分析助手
     * @return array|mixed
     */
    public static function getPayOrder($uid, $package=1)
    {
        if ($package == 1) {
            return mPackageOrder::getByWhere([
                'uid' => $uid,
                'package_id' => [self::PACKAGE_ID_1, self::PACKAGE_ID_2],
                'status' => mPackageOrder::STATUS_VALID
            ]);
        } else {
            return mPackageOrder::getByWhere([
                'uid' => $uid,
                'package_id' => self::PACKAGE_ID_3,
                'status' => mPackageOrder::STATUS_VALID
            ]);
        }

    }

    /**
     * 生成订单号
     * @param $packageId
     * @param $uid
     * @return string
     * @throws
     */
    public static function createOrderNo($packageId, $uid)
    {
        if ($packageId == self::PACKAGE_ID_3) {
            $orderList = self::getPayOrder($uid, $packageId);
        } else {
            $orderList = self::getPayOrder($uid);
        }
        if ($orderList) {
            throw new \Exception('你已购买');
        }
        if (OrderNoCache::dataLock($packageId . '-' . $uid, 1)) {
            $orderNo = self::genPackageOrderNo($packageId, $uid);
            $data = [
                'package_id' => $packageId,
            ];
            $key = 'package_' . $orderNo;
            OrderNoCache::setCache($key, $uid, $data);
        } else {
            throw new \Exception('你操作太频繁了');
        }
        return $orderNo;

    }

    /**
     * 生成需求分析助手订单号，要传递pacageId
     * @param $packageId
     * @param $uid
     * @return string
     * @throws
     */
//    public static function createAssisstantOrderNo($packageId, $uid)
//    {
//        $orderList = self::getPayOrder($uid, $packageId);
//        if ($orderList) {
//            Log::info('tttttt', [$packageId, $uid, $orderList]);
//            throw new \Exception('你已购买');
//        }
//        if (OrderNoCache::dataLock($packageId . '-' . $uid, 1)) {
//            $orderNo = self::genPackageOrderNo($packageId, $uid);
//            $data = [
//                'package_id' => $packageId,
//            ];
//            $key = 'package_' . $orderNo;
//            OrderNoCache::setCache($key, $uid, $data);
//        } else {
//            throw new \Exception('你操作太频繁了');
//        }
//        return $orderNo;
//
//    }

    /**
     * 订单号
     * @param $packageId
     * @param $uid
     * @return string
     */
    private static function genPackageOrderNo($packageId, $uid)
    {
        $microTime = bcmul(microtime(true), 10000);
        $microTime = sprintf('%s%s', date('His'), substr($microTime, -4, 3));
        $microTime = strtoupper(base_convert($microTime, 10, 32));
        $time = date('ymd');
        $parseId = strtoupper(base_convert($packageId, 10, 32));
        $hashUid = IdParse::hashUid($uid);
        $order = [
            $time,
            $microTime,
            $parseId,
            $hashUid
        ];
        $orderNo = implode('-', $order);
        $info = mPackageOrder::getByWhere(['order_no' => $orderNo]);
        if (!empty($info)) {
            self::genPackageOrderNo($packageId, $uid);
        }
        return $orderNo;
    }


    /**
     * 订单收货地址
     * @param $rawData
     * @return bool
     * @throws \Exception
     */
    public static function updateOrderAddress($rawData)
    {
        $phone = Phone::addExtendPhone($rawData['consigneePhone'], UserExtendPhoneScene::NEW_USER_PACKAGE_CONSIGNEE_PHONE);
        if (empty($phone)) {
            throw new \Exception('手机号加密异常', ApiAction::CODE_ERROR_VIEW_TOSTA);
        }
        $where['uid'] = $rawData['uid'];
        $where['order_no'] = $rawData['orderNo'];
        $data['consignee_name'] = $rawData['consigneeName'] ?? '';
        $data['consignee_phone_encrypt'] = $phone;
        $data['consignee_province'] = $rawData['province'] ?? '';
        $data['consignee_city'] = $rawData['city'] ?? '';
        $data['consignee_area'] = $rawData['area'] ?? '';
        $data['consignee_info_address'] = $rawData['infoAddress'] ?? '';
        $data['address_id'] = $rawData['addressId'] ?? '';
        $data['consignee_address'] = $rawData['consigneeDetailInfo'] ?? '';

        if (!mPackageOrder::updateData($data, $where)) {
            Log::error('package_order', [$data, $rawData, $where]);
            throw new \Exception('修改地址异常', ApiAction::CODE_ERROR_VIEW_TOSTA);
        }
        Log::info('order_address_success', [$data, $rawData]);
        return true;
    }

    /**
     * 创建订单
     * @param $uid
     * @param $orderNo
     * @param $payWay
     * @param $orderInfo
     * @param int $orderStatus
     * @return bool
     * @throws \Exception
     */
    public static function createOrder($uid, $orderNo, $payWay, $orderStatus = mPackageOrder::STATUS_NORMAL)
    {
        // 获取订单信息
        $key = 'package_' . $orderNo;
        $orderInfo = OrderNoCache::getCache($key);
        if (empty($orderInfo)) {
            throw new \Exception('下单过期');
        }
        //判断用户是否已经购买
        $hasOrderInfo = mPackageOrder::getByWhere([
            'package_id' => $orderInfo['package_id'],
            'uid' => $uid,
            'status' => mPackageOrder::STATUS_VALID
        ]);
        //已购买直接返回
        if ($hasOrderInfo) {
            return true;
        }
        $orderUid = PackageOrder::getUidByOrderNo($orderNo);
        if ($uid != $orderUid) {
            throw new \Exception('非用户订单', ErrorConst::ERROR_PAY_ORDER_INFO_UNKNOW);
        }
        $price = PackageOrder::PACKAGES[$orderInfo['package_id']]['price'];
        $info = mPackageOrder::getByWhere(['order_no' => $orderNo]);
        $data = [
            'order_no' => $orderNo,
            'uid' => $uid,
            'package_id' => $orderInfo['package_id'],
            'price' => $price,
            'status' => $orderStatus,
            'pay_way' => $payWay,
            'pay_time' => time()
        ];
        if (!$info) {
            mPackageOrder::insertData($data);
        } else {
            mPackageOrder::updateData($data, ['order_no' => $orderNo]);
        }
        return true;
    }

    /**
     * 获取uid
     * @param $orderNo
     * @return int|mixed
     */
    public static function getUidByOrderNo($orderNo)
    {
        $uid = 0;
        $arr = explode('-', $orderNo);
        if ($arr && count($arr) == 4) {
            $uid = $arr[3];
            $uid = IdParse::unHashUid($uid);
        }
        return $uid;
    }

    /**
     * 获取packageId
     * @param $orderNo
     * @return int|mixed
     */
    public static function getPackageIdByOrderNo($orderNo)
    {
        $packageId = 0;
        $arr = explode('-', $orderNo);
        if ($arr && count($arr) == 4) {
            $packageId = $arr[2];
            $packageId = base_convert($packageId, 32, 10);
        }
        return $packageId;
    }


    /**
     * 支付成功回调
     * @param $orderNo
     * @param $payWay
     * @param $payNo
     * @param $payAmount
     * @param $payTime
     * @param int $payVer
     * @throws \Exception
     */
    public static function callbackPaySucc($orderNo, $payWay, $payNo, $payAmount, $payTime, $payVer = 0)
    {
        Log::info('package-order-pay-callback', [$orderNo, $payWay, $payNo, $payAmount, $payTime, $payVer]);
        $orderUid = PackageOrder::getUidByOrderNo($orderNo);
        return self::createOrder($orderUid, $orderNo, $payWay);
    }


    /**
     * 发下行消息
     * @param $uid
     * @param $packageId
     */
    public static function sendSuccessMsg($uid, $packageId)
    {
        if ($uid) {
            //进入种草徽章队列
//            Queue::insertQueue('queue/Badge/HandleCenter', [
//                'uid' => $this->uid, //当前操作者uid
//                'action' => 'wiki_count', //用户行为
//                'obj_id' => $article_id,
//            ], Queue::QUEUE_BADGE);
            // 发送徽章和消息
            $url = Hhzurl::getDomain() . '/community/new-badge/detail' . "?id=24";
            $downLink = 'niceliving://webview/fullscreen?protego=' . urlencode(base64_encode(json_encode(['url' => $url])));
            $img = '';
            Log::info("下行物料如下：", ['uid' => $uid, 'totem_id' => 24, 'link' => $downLink, 'img' => $img]);
            //发送系统消息
            Queue::insertQueue('queue/Sysmsg/Send', [
                'msgCode' => 779,
                'to_uid' => $uid,
                'msgParams' => [
                    'img' => $img,
                    'link' => $downLink,
                ]
            ], Queue::QUEUE_DORAEMON);

        }
    }

    public static function getCashierAmount($orderNo)
    {
        $result = [];
        $uid = self::getUidByOrderNo($orderNo);
        try {
            $key = 'package_' . $orderNo;
            $orderInfo = OrderNoCache::getCache($key);
            if (empty($orderInfo)) {
                throw new \Exception('下单过期');
            }
            //判断用户是否已经购买
            $hasOrderInfo = mPackageOrder::getByWhere([
                'package_id' => $orderInfo['package_id'],
                'uid' => $uid,
                'status' => mPackageOrder::STATUS_VALID
            ]);
            //已购买直接返回
            if ($hasOrderInfo) {
                throw new \Exception('已购买');
            }
            $price = PackageOrder::PACKAGES[$orderInfo['package_id']]['price'];
            return [
                'order_no' => $orderNo,
                'uid' => $orderInfo['uid'],
                'package_id' => $orderInfo['package_id'],
                'title' => self::PACKAGES[$orderInfo['package_id']]['title'] ?? '',
                'original_price' => $price,
                'pay_amount' => $price,
                'paystop_time' => 0,
                'buy_num' => 1,
                'pay_ver' => 0,
            ];
        } catch (\Exception $e) {
            Log::info('收银台订单支付信息异常', [
                'uid' => $uid,
                'order_no' => $orderNo,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 物流签收该状态接口
     * @param $orderLogisticsNo
     * @return bool
     */
    public static function logisticsUpdateStatus($orderLogisticsNo)
    {
        $orderLogisticsLog = \Biz\service\package\OrderLogisticsLog::getLogisticsNo($orderLogisticsNo);
        $orderNo = $orderLogisticsLog['order_no'];
        $logistics = PackageLogistics::updateData(['status' => mPackageOrder::STATUS_RECEIVED, 'edittime' => time()], ['order_logistics_no' => $orderLogisticsNo]);
        $packageOrder = mPackageOrder::updateData(['status' => mPackageOrder::STATUS_RECEIVED, 'edittime' => time()], ['order_no' => $orderNo]);
        if ($logistics && $packageOrder) {
            return true;
        } else {
            return false;
        }
    }
}